<template>
  <div class="custom-el-plus">
    <el-dialog
      v-model="showDialog"
      width="auto"
      destroy-on-close
      :close-on-click-modal="false"
      align-center
      title="查看"
      @close="resetTaskInfo"
    >
      <div class="task-dialog">
        <div class="base-head">
          <div class="base-icon"></div>
          <p>基础信息</p>
        </div>
        <div class="task-ruleForm">
          <el-form
            ref="ruleFormRef"
            :model="state.taskFormData"
            label-width="auto"
            size="default"
            status-icon
          >
            <div class="top-item">
              <el-form-item label="任务名称" required>
                <span>{{ state.taskFormData.taskName }}</span>
              </el-form-item>
              <el-form-item label="任务编号" required>
                <span>{{ state.taskFormData.pkId }}</span>
              </el-form-item>
              <el-form-item label="任务状态" required>
                <div class="start-icon"></div>
                <span>{{ state.taskFormData.startup ? "启用" : "停用" }}</span>
              </el-form-item>
            </div>
            <div class="middle-item">
              <el-form-item label="自动任务" required>
                <div class="start-icon"></div>
                <span>{{ state.taskFormData.isAuto ? "启用" : "停用" }}</span>
              </el-form-item>
              <el-form-item label="启动时间">
                <span>{{ state.taskFormData.autoStartTime }}</span>
              </el-form-item>
              <el-form-item label="停止时间">
                <span>{{ state.taskFormData.autoEndTime }}</span>
              </el-form-item>
              <el-form-item label="事件类型">
                <el-tooltip
                  effect="dark"
                  :content="state.taskFormData.alarmDictPkIds"
                  placement="top"
                >
                  <span class="event-type-name">{{
                    state.taskFormData.alarmDictPkIds
                  }}</span>
                </el-tooltip>
              </el-form-item>
            </div>
            <div class="bottom-item">
              <el-form-item label="抽帧频率" required>
                <span>{{ state.taskFormData.frameCron }}</span>
              </el-form-item>
              <el-form-item label="任务描述">
                <span>{{ state.taskFormData.description }}</span>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="device-head">
          <div class="base-icon"></div>
          <p>关联设备管理</p>
          <el-button type="primary" @click="showMapMode">地图模式</el-button>
        </div>
        <div class="device-search-box">
          <!-- <span>行政区划</span>
          <el-select
            v-model="state.region"
            placeholder="全部"
            style="width: 16.328vw"
            popper-class="custom-query-select"
            clearable
          >
            <el-option
              v-for="item in regionList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select> -->
          <span>设备类型</span>
          <el-select
            v-model="state.deviceType"
            placeholder="全部"
            :value-on-clear="null"
            popper-class="custom-query-select"
            style="width: 16.328vw"
            clearable
          >
            <el-option
              v-for="item in state.deviceTypeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          <!-- <el-button plain @click="resetSearch">重置</el-button> -->
          <el-button type="primary" @click="searchDevice">查询</el-button>
        </div>
        <div class="device-table-box">
          <el-table
            :data="state.taskFormData.relativeDevice"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              :index="getDeviceIndex"
              label="序号"
              width="80"
            />
            <el-table-column prop="deviceId" label="设备ID" show-overflow-tooltip/>
            <el-table-column prop="deviceTypeName" label="设备类型" />
            <el-table-column prop="address" label="设备位置" show-overflow-tooltip/>
            <el-table-column prop="communicationTime" label="设备添加时间" />
            <el-table-column prop="onlineStatus" label="设备状态">
              <template #default="props">
                <div class="status-box">
                  <div v-if="props.row.onlineStatus" class="online-icon"></div>
                  <div v-else class="outline-icon"></div>
                  <span>{{ props.row.onlineStatus ? "在线" : "离线" }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="onlineStatus" label="设备启用状态">
              <template #default="props">
                <div
                  :class="props.row.status ? 'enable-box' : 'unable-box'"
                >
                  {{ props.row.status ? "启用" : "停用" }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="device-page-box">
          <el-pagination
            style="margin-left: auto"
            v-model:current-page="state.currentDevicePage"
            :small="small"
            :page-size="state.devicePageSize"
            :background="true"
            layout="total, prev, pager, next"
            :total="state.taskFormData.totalRelativeDevice.length"
            @current-change="handleCurrentDeviceChange"
          />
        </div>
        <div class="algorithm-head">
          <div class="base-icon"></div>
          <p>关联算法管理</p>
        </div>
        <div class="algorithm-table-box">
          <el-table
            :data="state.taskFormData.relativeAlgorithmList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              :index="getAlgorithmIndex"
              label="序号"
              width="80"
            />
            <el-table-column prop="name" label="算法名称" />
            <el-table-column prop="code" label="算法编码" />
            <el-table-column prop="creator" label="创建人" />
            <el-table-column prop="startOrShutdownTime" label="算法更新时间" />
            <el-table-column prop="status" label="算法状态">
              <template #default="props">
                <div
                  :class="
                    props.row.algorithmStatus ? 'enable-box' : 'unable-box'
                  "
                >
                  {{ props.row.algorithmStatus ? "启用" : "停用" }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="算法更新时间"
              width="200"
            />
          </el-table>
        </div>
        <div class="algorithm-page-box">
          <el-pagination
            style="margin-left: auto"
            v-model:current-page="state.currentAlgorithmPage"
            :small="small"
            :page-size="state.algorithmPageSize"
            :background="true"
            layout="total, prev, pager, next"
            :total="state.taskFormData.totalRelativeAlgorithmList.length"
            @current-change="handleCurrentAlgorithmChange"
          />
        </div>
      </div>
    </el-dialog>
    <el-dialog
      v-model="state.mapDialogVisible"
      width="auto"
      destroy-on-close
      align-center
      title="地图"
      @close="resetDeviceMap"
    >
      <div class="pic-dialog">
        <div class="img-content">
          <div class="map-container" id="devicePositionMap"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  computed,
  watch,
  getCurrentInstance,
  onActivated,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
  reactive,
  defineEmits,
  ref,
  h,
  nextTick,
} from "vue";

// 引入请求方法
import { wgs84togcj02, getMaxMinLatLng } from "@/utils/toolUtils.js";
import MapInit from "@/utils/mineMap/MapInit";
import { cronMapList } from "@/utils/constMapList.js";

// 引入图片
import device from "@/assets/img/liveData/mapPin.png";
const { proxy } = getCurrentInstance();

const props = defineProps({
  taskInfo: {
    type: Boolean,
    default: false,
  },
  taskCode: {
    type: String,
    default: "",
  },
});
const emit = defineEmits("update:taskInfo");
const showDialog = computed({
  get() {
    return props.taskInfo;
  },
  set(value) {
    emit("update:taskInfo", value);
  },
});
const state = reactive({
  taskFormData: {
    taskName: "",
    pkid: "",
    alarmDictPkIds: "",
    startup: 1,
    frameCron: "",
    description: "",
    isAuto: 0,
    autoStartTime: "",
    autoEndTime: "",
    createUser: "",
    relativeDevice: [],
    relativeAlgorithmList: [],
    totalRelativeDevice: [],
    totalRelativeAlgorithmList: [],
  },
  region: "",
  deviceType: null,
  currentDevicePage: 1,
  devicePageSize: 5,
  currentAlgorithmPage: 1,
  algorithmPageSize: 5,
  mapDialogVisible: false,
  mapImgsList: [
    {
      src: device,
      id: "device",
    },
  ],
  eventTypeList: [],
  deviceTypeList: [],
});
const mapObject = {
  darkMapObj: null,
  deviceMarker: null,
  congruentPoint: {
    type: "FeatureCollection",
    features: [],
  },
};
/* ====================================自定义方法================================= */
const getFormData = (data) => {
  state.taskFormData.taskName = data.taskName;
  state.taskFormData.pkId = data.pkId;
  state.taskFormData.description = data.description;
  state.taskFormData.startup = data.startup;
  state.taskFormData.isAuto = data.isAuto;
  state.taskFormData.autoStartTime = data.isAuto
    ? data.autoStartTime || "-"
    : "-";
  state.taskFormData.autoEndTime = data.isAuto ? data.autoEndTime || "-" : "-";
  let alarmList = (data.alarmDictPkIds || "").split(",");
  let alarmTypes = [];
  state.eventTypeList.forEach((item) => {
    if (alarmList.includes(item.pkId)) {
      alarmTypes.push(item.alarmType);
    }
  });
  state.taskFormData.alarmDictPkIds = alarmTypes.join(",");
  state.taskFormData.frameCron = cronMapList.find((item) => {
    return data.frameCron == item.value;
  })?.name;
  state.taskFormData.totalRelativeDevice = data.deviceInfoList || [];
  state.taskFormData.relativeDevice =
    state.taskFormData.totalRelativeDevice.slice(
      (state.currentDevicePage - 1) * state.devicePageSize,
      state.currentDevicePage * state.devicePageSize
    );
  state.taskFormData.totalRelativeAlgorithmList = data.algorithmInfoList || [];
  state.taskFormData.relativeAlgorithmList =
    state.taskFormData.totalRelativeAlgorithmList.slice(
      (state.currentAlgorithmPage - 1) * state.algorithmPageSize,
      state.currentAlgorithmPage * state.algorithmPageSize
    );
};
const initMap = (lat = 40.76546125305629, lng = 114.88923193324109) => {
  return new Promise((resolve, reject) => {
    mapObject.darkMapObj = new MapInit("devicePositionMap", {
      center: [lng, lat],
      pitch: 0,
      zoom: 16,
    });
    // mapObject.darkMapObj.on("click", onMouseClick);
    mapObject.darkMapObj.loadMapImgs(state.mapImgsList);
    let time = setInterval(() => {
      if (mapObject.darkMapObj && mapObject.darkMapObj.isStyleLoaded()) {
        clearInterval(time);
        resolve();
      }
    }, 100);
  });
};
const formCongruentData = (deviceData) => {
  return deviceData.map((item) => {
    return {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [+item.longitude, +item.latitude],
      },
      properties: item,
    };
  });
};
const addMarkers = (markerArr) => {
  mapObject.darkMapObj.addSource("deviceMarkerSrc", {
    type: "geojson",
    data: markerArr,
    generateId: true,
  });
  mapObject.darkMapObj.addLayer({
    id: "deviceMarkerLayer",
    type: "symbol",
    source: "deviceMarkerSrc",
    layout: {
      "icon-image": "device",
      "icon-size": 0.4,
      "icon-allow-overlap": true, //图标允许压盖
    },
  });
};
/* ====================================事件方法================================= */
const resetTaskInfo = () => {
  state.taskFormData = {
    taskName: "",
    pkid: "",
    alarmDictPkIds: "",
    startup: 1,
    frameCron: "",
    description: "",
    isAuto: 0,
    autoStartTime: "",
    autoEndTime: "",
    createUser: "",
    relativeDevice: [],
    relativeAlgorithmList: [],
    totalRelativeDevice: [],
    totalRelativeAlgorithmList: [],
  },
  state.deviceType = null;
  state.currentDevicePage = 1;
  state.currentAlgorithmPage = 1;
  state.eventTypeList = [];
  state.deviceTypeList = [];
}
const getDeviceIndex = (index) => {
  return (state.currentDevicePage - 1) * state.devicePageSize + index < 9
    ? "0" + ((state.currentDevicePage - 1) * state.devicePageSize + (index + 1))
    : (state.currentDevicePage - 1) * state.devicePageSize + (index + 1);
};
const getAlgorithmIndex = (index) => {
  return (state.currentAlgorithmPage - 1) * state.algorithmPageSize + index < 9
    ? "0" +
        ((state.currentAlgorithmPage - 1) * state.algorithmPageSize +
          (index + 1))
    : (state.currentAlgorithmPage - 1) * state.algorithmPageSize + (index + 1);
};
const searchDevice = () => {
  if (state.deviceType == null) {
    state.taskFormData.relativeDevice =
      state.taskFormData.totalRelativeDevice.slice(
        (state.currentDevicePage - 1) * state.devicePageSize,
        state.currentDevicePage * state.devicePageSize
      );
  } else {
    state.taskFormData.relativeDevice = state.taskFormData.totalRelativeDevice
      .filter((item) => {
        return item.deviceType == state.deviceType;
      })
      .slice(
        (state.currentDevicePage - 1) * state.devicePageSize,
        state.currentDevicePage * state.devicePageSize
      );
  }
};
const resetSearch = () => {
  state.deviceType = null;
};
const handleCurrentDeviceChange = (val) => {
  state.taskFormData.relativeDevice =
    state.taskFormData.totalRelativeDevice.slice(
      (state.currentDevicePage - 1) * state.devicePageSize,
      state.currentDevicePage * state.devicePageSize
    );
};
const handleCurrentAlgorithmChange = (val) => {
  state.taskFormData.relativeAlgorithmList =
    state.taskFormData.totalRelativeAlgorithmList.slice(
      (state.currentAlgorithmPage - 1) * state.algorithmPageSize,
      state.currentAlgorithmPage * state.algorithmPageSize
    );
};
const showMapMode = () => {
  state.mapDialogVisible = true;
  nextTick(() => {
    initMap().then(() => {
      let maxMinLatlng = getMaxMinLatLng(
        state.taskFormData.totalRelativeDevice.map((item) => {
          return { lng: item.longitude, lat: item.latitude };
        })
      );
      mapObject.darkMapObj.fitBounds(maxMinLatlng, {
        padding: { top: 100, bottom: 100, left: 100, right: 100 },
      });
      mapObject.congruentPoint.features = formCongruentData(
        state.taskFormData.totalRelativeDevice
      );
      addMarkers(mapObject.congruentPoint);
    });
  });
};
/* ====================================接口方法================================= */
const getTaskDetailInfo = async (pkId) => {
  const res = await proxy.$http.postWithBody("alarm/task/details", {
    pkId: pkId,
  });
  if (JSON.stringify(res) == "{}") {
    throw res;
  }
  return res;
};
const getEventList = async () => {
  const res = await proxy.$http.postWithBody("alarm/dict/selectAll", {
    pageNum: null,
    pageSize: null,
    startup: 1,
  });
  if (res == 0) {
    throw res;
  }
  return res;
};
const getDeviceTypeList = async () => {
  const res = await proxy.$http.getFun("device/type");
  if (JSON.stringify(res) == "{}") {
    throw res;
  }
  return res;
};
watch(
  () => props.taskCode,
  (newVal, oldVal) => {
    if (newVal) {
      getEventList().then((res) => {
        state.eventTypeList = res.list?.map((item) => {
          return {
            alarmType: item.alarmType,
            pkId: item.pkId,
          };
        });
      });
      getDeviceTypeList().then((res) => {
        state.deviceTypeList = res;
      });
      getTaskDetailInfo(newVal).then((res) => {
        getFormData(res);
      });
    }
  },
  {
    immediate: true,
  }
);

onMounted(() => {});
</script>
<style lang="scss" scoped>
.task-dialog {
  width: pxTvw(1270);
  max-height: pxTvh(880);
  overflow-y: scroll;
  :deep(.el-radio-group) {
    .el-radio__input.is-checked .el-radio__inner {
      border: 4px solid #2275f0 !important;
    }
    .el-radio__input.is-checked .el-radio__inner:after {
      background: transparent;
    }
  }
  :deep(.el-select) {
    .el-select__wrapper {
      width: 100%;
    }
  }
  & > .base-head {
    margin: pxTvh(24) pxTvw(16) 0 pxTvw(16);
    height: pxTvh(32);
    @include elasticFN(flex-start, center);
    & > .base-icon {
      width: pxTvw(4);
      height: pxTvh(13);
      background: #3174ff;
    }
    & > p {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      @include computed-font(16);
      color: #e8f1ff;
      margin-left: pxTvw(8);
    }
    & > .el-button {
      margin-left: auto;
      height: pxTvh(36);
    }
  }
  & > .task-ruleForm {
    margin: pxTvh(24) pxTvw(16) 0 pxTvw(16);
    .el-form {
      display: block;
    }
    .top-item {
      display: flex;
      color: #d3dfff;
      & > .el-form-item {
        width: 33.33%;
      }
      .start-icon {
        width: pxTvw(8);
        height: pxTvw(8);
        border: 4px solid #2275f0;
        border-radius: 50%;
        margin-right: pxTvw(8);
      }
    }
    .middle-item {
      display: flex;
      margin-top: pxTvh(24);
      color: #d3dfff;
      & > .el-form-item:nth-child(1) {
        width: 33.33%;
      }
      & > .el-form-item:nth-child(3) {
        margin-left: pxTvw(24);
      }
      & > .el-form-item:nth-child(4) {
        width: 33.33%;
        margin-left: auto;
      }
      .start-icon {
        width: pxTvw(8);
        height: pxTvw(8);
        border: 4px solid #2275f0;
        border-radius: 50%;
        margin-right: pxTvw(8);
      }
      .event-type-name {
        max-width: 330px;
        @include overstepForRow();
      }
    }
    .bottom-item {
      display: flex;
      color: #d3dfff;
      margin: pxTvh(24) 0;
      & > .el-form-item:nth-child(1) {
        width: 33.33%;
      }
    }
  }
  & > .device-head,
  & > .algorithm-head {
    margin: 0 pxTvw(16) 0 pxTvw(16);
    height: pxTvh(34);
    @include elasticFN(flex-start, center);
    & > .base-icon {
      width: pxTvw(4);
      height: pxTvh(13);
      background: #3174ff;
    }
    & > p {
      font-family: PingFang SC, PingFang SC,sans-serif;
      font-weight: 500;
      @include computed-font(16);
      color: #e8f1ff;
      margin-left: pxTvw(8);
    }
    & > .el-button {
      margin-left: auto;
      height: pxTvh(36);
    }
  }
  & > .device-search-box {
    @include elasticFN(flex-start, center);
    height: pxTvh(32);
    margin: pxTvh(16) pxTvw(16);
    font-family: PingFang SC, PingFang SC,sans-serif;
    font-weight: 400;
    @include computed_font(14);
    color: #ffffff;
    & > .el-select {
      margin-left: pxTvw(12);
    }
    & > span:nth-of-type(2) {
      margin-left: pxTvw(24);
    }
    & > .el-button:nth-of-type(1) {
      margin-left: pxTvw(24);
      height: pxTvh(36);
    }
  }
  & > .device-table-box {
    margin: 0 pxTvw(16);
    .status-box {
      @include elasticFN(flex-start, center);
      & > .online-icon {
        margin-right: pxTvw(8);
        width: pxTvw(8);
        height: pxTvw(8);
        background: #34ad54;
        border-radius: 50%;
      }
      & > .outline-icon {
        margin-right: pxTvw(8);
        width: pxTvw(8);
        height: pxTvw(8);
        background: #a5adba;
        border-radius: 50%;
      }
    }
    .enable-box {
      width: pxTvw(56);
      height: pxTvh(24);
      border-radius: pxTvw(12);
      border: 1px solid #34ad54;
      color: #34ad54;
      @include elasticFN(center, center);
    }
    .unable-box {
      width: pxTvw(56);
      height: pxTvh(24);
      border-radius: pxTvw(12);
      border: 1px solid #a5adba;
      color: #a5adba;
      @include elasticFN(center, center);
    }
  }
  & > .device-page-box {
    margin: pxTvh(16) pxTvw(16) pxTvh(24) pxTvw(16);
  }
  & > .algorithm-table-box {
    margin: pxTvh(16) pxTvw(16) 0 pxTvw(16);

    .enable-box {
      width: pxTvw(56);
      height: pxTvh(24);
      border-radius: pxTvw(12);
      border: 1px solid #34ad54;
      color: #34ad54;
      @include elasticFN(center, center);
    }
    .unable-box {
      width: pxTvw(56);
      height: pxTvh(24);
      border-radius: pxTvw(12);
      border: 1px solid #a5adba;
      color: #a5adba;
      @include elasticFN(center, center);
    }
  }
  & > .algorithm-page-box {
    margin: pxTvh(16) pxTvw(16) 0 pxTvw(16);
  }
}
.pic-dialog {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  .img-content {
    margin-top: pxTvh(16);
    padding: 0 pxTvh(16);
    color: rgba(207, 219, 252, 0.8);
    box-sizing: border-box;
    & > #devicePositionMap {
      width: pxTvw(1168);
      height: pxTvh(657);
    }
  }
}
</style>